import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input, Message, NumberPicker, Switch } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, column, model } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import TauTable from '@/components/TauTable';
import DialogChange from './DialogChange';
import DialogDriverChange from './DialogDriverChange';
import DialogDIChange from './DialogDIChange';

const FromItem = Form.Item;

const modelVI = model.vehicleInfos;
const modelDI = model.vehicleInfos.driverInfos;

const DataForm = ({ id, onCancel, modal, onSubmit, onPass, ...formProps }) => {
  const { memberStore: store, ruleStore, loginStore } = useStore();
  const { show, record, toClose } = modal;
  const [member] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  const [groupDataSource, setGroupDataSource] = useState([]);
  const [portsDataSource, setPortsDataSource] = useState([]);
  const [state, setState] = useState([]);
  const [dIState, setDIState] = useState([]);
  const [curCharge, setCurCharge] = useState();
  const [driverCurChange, setDriverCurCharge] = useState();
  const [dICurCharge, setDICurCharge] = useState();
  const [driverMenu, setDriverMenu] = useState([]);
  const [idx, setIdx] = useState(-1);
  const [dIIdx, setDIIdx] = useState(-1);
  const { isAdmin } = loginStore;
  const [loading, setLoading] = useState(false);
  const [companyInputDialogVisible, setCompanyInputDialogVisible] = useState(false);
  const [rejectCompanyUpdate, setRejectCompanyUpdate] = useState(false);
  const [currentCompanyName, setCurrentCompanyName] = useState(false);
  const [isCompanyName, setIsCompanyName] = useState(false);

  function restCompanyInfo() {
    setRejectCompanyUpdate(false);
    setCurrentCompanyName(false);
    setIsCompanyName(false);
  }

  useEffect(() => {
    if (toClose?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      const data = await store.getGroup({ search: {}, pg: { page: 0, size: 999, sort: ['crDate;desc'] } });
      const port = await store.getDicts('port');
      const tempMenu = port.reduce((acc, cur) => {
        acc[cur.value] = cur.label;
        return acc;
      }, {});
      setDriverMenu(tempMenu);
      setPortsDataSource(port);
      setGroupDataSource(data);
      if (id) {
        const res = await store.get(id);
        setCurrentCompanyName(() => !!res?.companyName);
        setRejectCompanyUpdate(() => store._tableStatus == -1);
        await initExtras(res);
        editCtx.origin = _.cloneDeep(res);
        _.assign(member, res);
      } else {
        const findObj = toJS(ruleStore._groups).find((p) => p.value == ruleStore._group_id);
        _.set(member, 'status', 0);
        _.set(member, 'takeOrderStatus', false);
        _.set(member, 'groupId', ruleStore._group_id);
        _.set(member, 'groupName', findObj?.label);
        _.set(member, 'vehicleInfos', []);
      }
    })();
    return () => {
      restCompanyInfo();
    };
  }, []);

  async function initExtras(res) {
    try {
      const { companyName = undefined, phone } = res;
      const vehicles = await store.getVehicles({ search: companyName ? { companyName } : { phone }, pg: { size: 10, page: 0, sort: ['crDate;desc'] } });
      const drivers = await store.getMemberDriver({ phone });
      const tempVehicle = vehicles.map((p) => ({
        ...p,
        driverIds: p.driverInfos.map((j) => j.mainPhone),
      }));
      setState(tempVehicle);
      setDIState(drivers);
    } catch (error) {
      console.log('🚀 _ file: DataForm.jsx:79 _ error:', error);
      throw error;
    }
  }

  const overrideModel = {
    groupId: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} disabled={ruleStore._group_id} dataSource={groupDataSource} />,
      },
    },
    ports: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} dataSource={portsDataSource} mode="multiple" />,
        itemProps: { required: true },
      },
    },
    vehicleInfos: {
      ui: {
        renderer: () => {
          return (
            <>
              {/* {(show !== 'view' && member?.type === '0') &&
                <div style={{ marginLeft: 0 }}>
                  <span>{t`是否可维护公司车辆信息：`}</span>
                  <Switch
                    checked={member.maintainVehicleFlag || false}
                    checkedChildren={t`是`}
                    unCheckedChildren={t`否`}
                    autoWidth
                    loading={loading}
                    onChange={(v) => handleOnEditVehicleFlag(v)}
                    size="small"
                  />
                </div>} */}
              {!isViewMode && <Button type="primary" onClick={() => handleAdd('VI')}>{t`添加车辆信息`}</Button>}
              <TauTable
                hidePagination
                dataSource={state}
                onRowClick={(_, index) => setIdx(index)}
                columns={[
                  { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                  column('mainlandLicense', { width: 100 }, modelVI),
                  column('hkLicense', { width: 100 }, modelVI),
                  column('ports', {
                    width: 150,
                    cell: (v) => {
                      const temp = v?.map((p) => driverMenu[p]);
                      return (<>{temp?.join('，')}</>);
                    },
                  }, modelVI),
                  column('vehicleModel', { width: 100 }, modelVI),
                  column('passengerCapacity', { width: 88 }, modelVI),
                  column('driverInfos', {
                    width: 200,
                    cell: (v) => {
                      return <>{v?.map((p) => p.name)?.join('、')}</>;
                    },
                  }, modelVI),
                  column('attachments', {
                    width: 66,
                    cell: (v, i, r) => {
                      const count = v?.reduce((acc, item) => {
                        acc += item.binaryId?.length;
                        return acc;
                      }, 0);
                      return <Button text type="primary" onClick={() => handleEdit(r, 'VI')}>{v ? `${count} 张` : t`无`}</Button>;
                    },
                  }, modelVI),
                  {
                    title: t`操作`,
                    dataIndex: 'refundNumber',
                    width: 160,
                    cell: (_, i, r) => (
                      <>
                        <Button key={'1'} text type="primary" onClick={() => handleEdit(r, 'VI')}>{t`编辑`}</Button>
                        <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                        <Button
                          key={'3'}
                          text
                          style={{ color: 'red' }}
                          type="normal"
                          onClick={() => handleRemove(i, 'VI')}
                        >{t`删除`}
                        </Button>
                      </>
                    ),
                  },
                ]}
              />
            </>
          );
        },
        span: 4,
      },
      driverInfos: {
        ui: {
          renderer: () => {
            return (
              <>
                {!isViewMode && member?.type == '0' && <Button type="primary" onClick={() => handleAdd('DI')}>{t`添加司机信息`}</Button>}
                <TauTable
                  hidePagination
                  dataSource={dIState}
                  onRowClick={(_, index) => setDIIdx(index)}
                  columns={[
                    { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                    column('name', { width: 200 }, modelDI),
                    column('mainPhone', { width: 260 }, modelDI),
                    column('hkPhone', { width: 260 }, modelDI),
                    column('wxAccount', { width: 260 }, modelDI),
                    {
                      title: t`操作`,
                      dataIndex: 'refundNumber',
                      width: 160,
                      cell: (_, i, r) => (
                        <>
                          <Button key={'1'} text type="primary" onClick={() => handleEdit(r, 'DI')}>{t`编辑`}</Button>
                          <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                          <Button
                            key={'2'}
                            text
                            style={{ color: 'red' }}
                            type="normal"
                            onClick={() => handleRemove(i, 'DI')}
                          >{t`删除`}
                          </Button>
                        </>
                      ),
                    },
                  ]}
                />
              </>
            );
          },
          span: 4,
        },
      },
    },
    points: {
      ui: {
        renderer: (v) => <NumberPicker disabled={!isAdmin && show === 'edit'} value={v} style={{ width: '100%' }} />,
        itemProps: { required: true },
      },
    },
    // companyName: {
    //   label: t`所属公司`,
    //   ui: {
    //     renderer: (v) => (
    //       <>
    //         <FromItem>
    //           <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'nowrap' }}>
    //             {companyInputDialogVisible ? <Input style={{ width: 180, marginRight: 10 }} disabled={rejectCompanyUpdate} onChange={handleOnChangeCompanyName} value={v} /> : <TauSimpleSelect disabled={rejectCompanyUpdate} style={{ width: 180, marginRight: 10 }} hasClear={false} value={v} dataSource={rootStore.memberStore.companiesNames} onChange={handleOnChangeCompanyName} />}
    //             <FromItem>
    //               <Button type="primary" disabled={rejectCompanyUpdate} onClick={() => handleAddCompanyName()}>{companyInputDialogVisible ? t`选择公司` : t`手动输入公司`}</Button>
    //             </FromItem>
    //           </div>
    //         </FromItem>
    //       </>),
    //   },
    // },
  };

  const handleAddCompanyName = () => {
    setCompanyInputDialogVisible(() => !companyInputDialogVisible);
    _.set(member, 'companyName', '');
  };

  const handleOnEditVehicleFlag = async (status) => {
    const { phone, id: memberId } = toJS(member);
    if (show === 'add') {
      _.set(member, 'maintainVehicleFlag', status);
    } else {
      setLoading(true);
      try {
        await store.updateVehicleFlag({ phone, status });
        const res = await store.get(memberId);
        _.assign(member, res);
        Message.success({ content: t`更新成功` });
      } catch (error) {
        Message.error({ content: t`更新失败`, duration: 7000 });
        throw error;
      } finally {
        setLoading(false);
      }
    }
  };

  const handleOnChangeCompanyName = async (e) => {
    _.set(member, 'companyName', e);
    if (show !== 'add' && !currentCompanyName && e) {
      setIsCompanyName(() => true);
      _.set(member, 'saveVehicle', true);
    }
  };

  const ADDTYPE = {
    VI: () => setState((pre) => {
      const data = [...pre];
      setIdx(data.length);
      setCurCharge({
        id: new Date().getTime(),
      });
      return data;
    }),
    DI: () => setDIState((pre) => {
      const data = [...pre];
      setDIIdx(dIState.length);
      setDICurCharge({
        driverId: new Date().getTime(),
      });
      return data;
    }),
  };

  const REMOVETYPE = {
    VI: (i) => setState((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    }),
    DI: (i) => setDIState((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    }),
  };

  const EDITTYPE = {
    VI: (r) => setCurCharge(r),
    DI: (r) => setDICurCharge(r),
  };

  const handleAdd = (type) => {
    if (member?.type === '1' && state?.length === 1) {
      Message.error({ content: t`司机成员只能添加一辆车！`, duration: 7000 });
      return;
    }
    ADDTYPE[type]?.();
  };

  const handleEdit = (r, type) => {
    EDITTYPE[type]?.(r);
  };

  const handleRemove = (i, type) => {
    REMOVETYPE[type]?.(i);
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const tempData = _.cloneDeep(state);
    tempData[idx] = values;
    const tempDiData = _.cloneDeep(dIState);
    const result = values?.driverIds?.reduce((acc, item2) => {
      const foundItem = tempDiData.find((p) => p.mainPhone === item2);
      if (foundItem) {
        acc.push(foundItem);
      }
      return acc;
    }, []);
    tempData[idx].driverInfos = result || [];
    setState(tempData);
    setCurCharge(false);
  };

  const dIChargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const tempData = _.cloneDeep(dIState);
    tempData[dIIdx] = values;
    setDIState(tempData);
    setDICurCharge(false);
  };

  const driverChargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const { driverIds } = values;
    const tempData = _.cloneDeep(state);
    tempData[idx].driverIds = driverIds;
    setState(tempData);
    setDriverCurCharge(false);
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(member, name, value);
    if (name === 'groupId') {
      const findObj = item?.field?.fieldsMeta?.groupId?.inputValues[2];
      _.set(member, 'groupName', findObj?.label);
    }
    if (name === 'type') {
      setDIState([]);
      setState([]);
    }
    if (name === 'phone') {
      if (value.length == 11) {
        (async () => {
          const res = await store.params_search({
            search: {
              phone: value,
            },
            pg: { page: 0, size: 10, sort: [] },
          });
          if (res?.length > 0) {
            const temp = store.removeUnwantedProperties(res[0]);
            await initExtras(res[0]);
            _.assign(member, temp);
            if (temp?.companyName && show === 'add') {
              setRejectCompanyUpdate(true);
            }
            if (show === 'edit') {
              setCurrentCompanyName(() => !!temp?.companyName);
              setIsCompanyName(false);
            }
          } else {
            restCompanyInfo();
            _.set(member, 'companyName', '');
          }
        })();
      }
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    if (show == 'add' && member.id && (member.groupId == ruleStore._group_id)) {
      Message.error({ content: t`已存在此成员，请勿重复添加!`, duration: 7000 });
      return;
    }
    const findObj = toJS(ruleStore._groups).find((p) => p.value == ruleStore._group_id);
    _.set(member, 'groupId', ruleStore._group_id);
    _.set(member, 'groupName', findObj?.label);
    const tempState = _.cloneDeep(state);
    const tempStateDriver = _.cloneDeep(dIState);
    const filterTempState = tempState.map((p) => {
      const clone = { ...p };
      delete clone.driverIds;
      return clone;
    });
    _.set(member, 'vehicleInfos', filterTempState);
    if (member?.type === '1' && dIState?.length === 0) {
      const { fullname, phone, hkPhone, wxAccount } = member || {};
      const tempDI = [
        { name: fullname, mainPhone: phone, hkPhone, wxAccount },
      ];
      for (const item of tempState) {
        item.driverInfos = tempDI;
      }
    } else {
      for (const item of tempState) {
        const { phone } = member || {};
        item.phone = phone;
        item.driverInfos = tempStateDriver;
      }
    }
    _.set(member, 'vehicleInfos', tempState);
    onSubmit?.(member);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleOnPass = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    onPass?.(toJS(member));
  };

  return (
    <Form {...formProps} value={member} onChange={handleChange} inline useLabelForErrorMessage>
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={member}
        mode={show}
        overrideModel={overrideModel}
        fields={['groupId', 'memberId', 'fullname', 'nickname',
          'phone', 'hkPhone', 'wxAccount', 'type', 'points',
        ].concat(member?.type === '0' && show !== 'add' ? ['companyName'] : [])
          .concat(isCompanyName ? ['saveVehicle'] : [])
          .concat(['recordRemarks', 'consoleRemarks'])}
      />
      <TitleGrid title={t`车辆及司机信息`} />
      <FieldsGrid
        formData={member}
        mode={show}
        overrideModel={overrideModel}
        fields={['vehicleInfos', 'vehicleInfos.driverInfos']}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          {show == 'edit' && store._tableStatus == '-1' && <Form.Submit validate type="primary" style={{ marginLeft: 8 }} onClick={handleOnPass}>{t`通过`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <DialogChange
        member={toJS(member)}
        curCharge={curCharge}
        setCurCharge={setCurCharge}
        portsDataSource={portsDataSource}
        dIState={dIState}
        setDIState={setDIState}
        setIdx={setIdx}
        setDIIdx={setDIIdx}
        chargeOnSubmit={chargeOnSubmit}
        dICurCharge={dICurCharge}
        setDICurCharge={setDICurCharge}
        dIChargeOnSubmit={dIChargeOnSubmit}
      />
      <DialogDriverChange
        driverCurChange={driverCurChange}
        setDriverCurCharge={setDriverCurCharge}
        dIState={dIState}
        driverChargeOnSubmit={driverChargeOnSubmit}
      />
      <DialogDIChange
        dICurCharge={dICurCharge}
        setDICurCharge={setDICurCharge}
        dIChargeOnSubmit={dIChargeOnSubmit}
      />
    </Form>
  );
};

export default observer(DataForm);
